package com.cheetah.thread;

import com.cheetah.concurrent.ThreadPoolExecutorFactory;
import com.cheetah.config.Config;
import com.cheetah.config.ThreadPoolConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;


@Component
@Slf4j
public class ThreadPoolManager {

    public static final String HANDLER_POOL_PREFIX = "handler-pool-";
    private ThreadPoolExecutorFactory executorFactory = ThreadPoolExecutorFactory.getInstance();

    @Autowired
    private ThreadPoolConfig threadPoolConfig;


    //初始化线程池
    @PostConstruct
    public void init(){
        Map<String, Config> cfgs = threadPoolConfig.getPoolMap();
        //没有配置线程池时，启动默认线程池
        if(cfgs.size() <= 0){
            Config config = new Config();
            config.setPoolName("default");
            config.setThreadCount(100);
            config.setQueueLength(1000);
            config.setTimeout(10);
            cfgs.put("default",config);
        }

        cfgs.forEach((k,v) -> {
           executorFactory.createExecutor(HANDLER_POOL_PREFIX + k, v.getThreadCount(),
                   v.getQueueLength(), v.getTimeout());
           log.info("create thread pool. name:{}, threadCount:{}, queueLength:{}, timeout:{}",
                   HANDLER_POOL_PREFIX + v.getPoolName(), v.getThreadCount(), v.getQueueLength(), v.getTimeout());
        });
    }

    public ThreadPoolExecutorFactory getExecutorFactory(){
        return executorFactory;
    }

    //停止线程池
    public void stop(){
        executorFactory.shutdownAll();
    }


}
